/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 *
 * this function will clear all the form data
 * @attr: is an array of input and textarea
 */
var exitCode={"PP_EXIT":0};
function clearFormData(attr){
    for(var i=0; i<attr.length; i++){
        $(attr[i]).val("");
        $(attr[i]).css("border-color","grey");
    }
}
/*
 * resetModal
 *
 */
function resetModal(params){
    for(var i in params){
        var currentObj=params[i];
        if(i=="hide"){
            for(var j in currentObj){
                if(j=="hideEle"){
                    $(currentObj[j]).hide();
                }else{
                    $(currentObj[j]).show();
                }
            }
        }else if(i=="attr"){
            clearFormData(currentObj);
        }
    }
}
/*
 * Clear every inputs value in the modal box
 * @param: dialog - the modal object
 */
function clearSignupModal(dialog){
    var inputs=$(dialog).find("input[type!=button]");
    var textareas= $(dialog).find("textarea");
    if(inputs.length>0){
        $(inputs).each(function(){
            $(this).val("");
        });
    }
    if(textareas.length >0){
        $(textareas).each(function(){
           $(this).val("");
        });
    }
}
/*
 * submit the form to signup controller and let eh controller take it from there
 */
function userSignup(dialog){
    var signupForm = $(dialog).find("form");
    signupForm.submit();
}

/*
 * retrive tweets from twitter
 * @tweetUn: the twitter username
 * @tweetCount: the total number of counts coming back
 */
function retriveTweets(tweetUn,tweetCount){
    if(tweetUn==null){tweetUn="ve_vive";}
    if(tweetCount==null){tweetCount=2;}
    var url= "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+tweetUn+"&count="+tweetCount;
    $.ajax({
        url:url,
        dataType:"jsonp",
        success:applyTweets,
        type:"GET"
    });
}

function applyTweets(tweets,status){
    if(status!="success"){return;}
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var container= $(".twitterFeed");
    var tweetBird = "application/images/bird_16_blue.png";
    for(var i=0;i<tweets.length;i++){
        var tweet=tweets[i];
        var createdTime=tweet.created_at;
        var authorName = tweet.user.name;
        var text = tweet.text;
        var reply=tweet.reply;
        var twId = tweet.id_str;
        var tweetContainer = $("<div>").addClass("tweetbox").addClass("shadow-box").attr("id",twId);
        var authorImage = $("<img/>").attr("class","avatar").attr("src",tweet.user.profile_image_url).attr("alt","avatar");
        var tweetlist = $("<ul>");
        //start making list

        //making the author info
        var tweetInfo=$("<li>").addClass("tweetinfo");
        var link=$("<a>").attr("href","https://twitter.com/#!/ve_vive").attr("target","_blank").text(authorName);
        var authorSpan=$("<span>").text(authorName);
        tweetInfo.append(link).append(authorSpan);

        //making the tweet feeds
        var tweetInfoFeed=$("<li>").addClass("tweetinfo").addClass("feed");
        text=text.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(url) {
            return '<a href="'+url+'">'+url+'</a>';
        }).replace(/B@([_a-z0-9]+)/ig, function(reply) {
            return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
        })
        tweetInfoFeed.append(text);

        //making the tweet functions
        var tweetInfoFuncs=$("<li>").addClass("tweetinfo");
        var funcsUl=$("<ul>");
        funcsUl.append($("<li>").append($("<img>").attr("src",tweetBird).attr("alt","tweetBird")));
        var tweetTime=new Date(createdTime);
        var filterTime=tweetTime.getDate()+" "+months[tweetTime.getMonth()];
        funcsUl.append($("<li>").append($("<span>").text(filterTime)));
        tweetInfoFuncs.append(funcsUl);
        tweetlist.append(tweetInfo).append(tweetInfoFeed).append(tweetInfoFuncs);
        tweetContainer.append(authorImage).append($("<div>").append(tweetlist));
        container.append(tweetContainer);
    }
}

function editUserEvent(swch){
    if(swch===true){
        $("#editEventModal").dialog("open");
    }
}

function swapEvent(curBox){
    var eName=$(curBox).find("li#eventboxName").text();
    var eDesc=$(curBox).find("input[name='eventboxdesc']").val();
    var eCost=$(curBox).find("input[name='cost']").val();
    var eid=$(curBox).attr("id").split("-");
    var eid=eid[1];
    
    removeAttr(curBox);
    $("#curEvtName").text(eName);
    $("#curEvtDesc").text(eDesc);
    var paymentInfoList=$("<ul>");
    var paymentInfoName=$("<li>").text("Event name: "+eName);
    var paymentInfoDesc=$("<li>").text("Event Description: "+eDesc);
    var paymentInfoCost=$("<li>").text("Event Cost: "+eCost);

    paymentInfoList.append(paymentInfoName).append(paymentInfoDesc).append(paymentInfoCost);
    if(eName.toLowerCase()=="party"){
        var $activitiesContainer = $("<div/>").addClass("extraActivities").append($("<span/>").addClass("actText").text("Would you be interest in joining our summer outdoor competition?"));
        var $ul=$("<ul/>");
        var $accept=$("<input/>").prop("type","radio").prop("name","vollyball").prop("value","1").prop("checked","checked");
        var $decline=$("<input/>").prop("type","radio").prop("name","vollyball").prop("value","0");
        var $vollyball = $("<li/>").append($("<label/>").text("Vollyball")).append($accept).append($("<label/>").text("Accept")).append($decline).append($("<label/>").text("Decline"));
        $ul.append($vollyball);
        var $wpAccept=$("<input/>").prop("type","radio").prop("name","beerpong").prop("value","1").prop("checked","checked");
        var $wpDecline=$("<input/>").prop("type","radio").prop("name","beerpong").prop("value","0");
        var $waterPong = $("<li/>").append($("<label/>").text("Water-Pong")).append($wpAccept).append($("<label/>").text("Accept")).append($wpDecline).append($("<label/>").text("Decline"));
        $ul.append($waterPong);
        paymentInfoList.append($("<li/>").append($activitiesContainer.append($ul)));
    }
    $("#paymentInfo").html(paymentInfoList);
    $("#hiddenEid").val(eid);
}
function removeAttr(curBox){
    var shouldRemove=$(curBox).find("input[name='isJoin']").val();
  
    if(shouldRemove=="1"){
        $("input[name='join']").attr("checked","").attr("disabled","disabled");
    }else{
         $("input[name='join']").removeProp("checked").removeProp("disabled");
    }
}

function formIntegrity(curForm){
    var shouldSend=true;
    var inputs=$(curForm).find("[customtype]");//this will get all the customType inputs
    $(inputs).each(function(){
        var rvar=checkIntegrity(this);
        if(rvar==false){
		shouldSend=false;
	}else{
            if(exitCode[rvar]==0){
                var checkoutEid=$("#hiddenEid").val();
                $("input.checkoutEid").val(checkoutEid);
                 $("#paymentModal").dialog("open");
                shouldSend=false;
                return false;//meaning it's a paypal payment exit
            }
        }
    });
    var pwd=$(curForm).find("input[customtype='password']");
    if(checkPasswordMatch(pwd)==false){
	shouldSend=false;
	}
   return shouldSend;
}

function checkIntegrity(curEle){
    var type=$(curEle).attr("customtype");
    if(type=="switch"){// testing the checkbox
	var shouldSend=checkboxIntegrity(curEle);
        if(shouldSend==true){
            if($(curEle).attr("name")=="join"){
                return "PP_EXIT";
            }
        }
        return shouldSend;
    }else if(type=="number"){return checkNumberIntegrity(curEle);
    }else if(type=="str"){return checkStrIntegrity(curEle);
    }else if(type=="email"){return checkEmailIntegrity(curEle)
    }else if(type=="none"){return checkEmptyIntegrity(curEle);}

   // return true;
}

function checkboxIntegrity(curEle){
	var shouldSend=true;
        if($(curEle).attr("disabled")!=undefined){
		shouldSend=false;
	}
	if(!$(curEle).is(":checked")){
		shouldSend=false;
	}
	return shouldSend;
}
function checkNumberIntegrity(curEle){
    var reg=/\d/g;
    var result= reg.test($(curEle).val());
    if(!result){throwInputError(curEle);}else{throwInputError(curEle,true)}
    return result;
}
function checkStrIntegrity(curEle){
    var reg=/[a-zA-Z]/g;
    var result=reg.test($(curEle).val());
    if(!result){throwInputError(curEle);}else{throwInputError(curEle,true)}
    return result;
}
function checkEmailIntegrity(curEle){
    var reg=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9][a-zA-Z0-9.-]+[\.]{1}[a-zA-Z]{2,4}$/;
    var result=reg.test($(curEle).val());
    if(!result){throwInputError(curEle);}else{throwInputError(curEle,true)}
    return result;
}
function checkEmptyIntegrity(curEle){
    var val=$(curEle).val();
    if(val==""){
        throwInputError(curEle);
        return false;
    }else{
        throwInputError(curEle,true);
        return true;
    }
}
function checkPasswordMatch(pwd){
    if($(pwd.get(0)).val()==$(pwd.get(1)).val()){
        return true;
    }else{return false;}
}
function throwInputError(curEle,clearError){
    if(clearError){$(curEle).css("border","");
    }else{$(curEle).css("border","2px solid #FE2E2E");}
}
function drawPaypalExpress(eid){
    var form=$("<form>").attr("method","post").attr("action","/expresscheckout");
    var hiddenInput=$("<input>").attr("type","hidden").attr("value",eid).attr("name","eid");
    var imageBtn=$("<input>").attr("type","image").attr("name","submit").attr("src","https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif");
    form.append(hiddenInput).append(imageBtn);
    $("#paymentModal").append(form);
}
function editProfile(){
     $(".userprofilemodal").dialog("open");
}
function editProfilePic(){
    $("#uploadModal").dialog("open");
}
function openDisclaimer(){
    $("#disclaimerModal").dialog("open");
}
